package com.fs.uc.base;

import io.minio.*;
import io.minio.http.Method;
import io.quarkus.arc.log.LoggerName;
import org.jboss.logging.Logger;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import java.io.InputStream;

/**
 * @author 崔超
 * 2021/12/17
 */
@ApplicationScoped
public class MinioUtil {
    private final static String BUCKET_NAME = "usercenter";
    private final MinioClient client;

    @LoggerName("MinioUtil")
    Logger logger;

    public MinioUtil(MyConfig config) {
        MyConfig.Minio minio = config.minio();
        client = MinioClient.builder()
                .endpoint(minio.address())
                .credentials(minio.accessKey(), minio.secretKey())
                .build();
        try {
            boolean found = client.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!found) {
                client.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadImage(String filename, InputStream fileStream) throws Exception {
        PutObjectArgs arg = PutObjectArgs.builder().bucket(BUCKET_NAME).object(filename)
                .stream(fileStream, -1, 5242880).contentType("image/jpeg").build();
        client.putObject(arg);
    }

    public boolean exist(String filename) {
        try {
            client.statObject(StatObjectArgs.builder().bucket(BUCKET_NAME).object(filename).build());
            return true;
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return false;
        }
    }

    public String preview(String filename) throws Exception {
        String minioUrl = client.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(BUCKET_NAME)
                        .object(filename)
                        .expiry(24 * 60 * 60)
                        .build());
        return minioUrl.replaceFirst("http://.*?/","/minio/");
    }

    public void moveFile(String src, String dest) throws Exception {
        CopySource source = CopySource.builder().bucket(BUCKET_NAME).object(src).build();
        client.copyObject(CopyObjectArgs.builder().bucket(BUCKET_NAME).object(dest).source(source).build());
        client.removeObject(RemoveObjectArgs.builder().bucket(BUCKET_NAME).object(src).build());
    }

    public String getFilenameFromPreviewUrl(String previewUrl) {
        int start = previewUrl.indexOf("/" + BUCKET_NAME);
        int end = previewUrl.indexOf("?");
        return previewUrl.substring(start + 12, end);
    }

}
